#include "../log/ckflog.hpp"

using namespace ckflogs;
// 以时间为单位的滚动文件
class RollByTimeLogSink : public LogSinker
{
private:
    std::string prefix_;
    std::ofstream cur_ofs_;
    time_t create_time_;
    time_t max_time_;

public:
    enum RollTimeType
    {
        RTT_SEC = 0,
        RTT_MIN,
        RTT_HOUR,
    };

public:
    RollByTimeLogSink(const std::string &prefix, RollTimeType rtt = RollTimeType::RTT_SEC)
        : prefix_(prefix), create_time_(0), max_time_(0)
    {
        switch (rtt)
        {
        case RTT_SEC:
            max_time_ = 1;
            break;
        case RTT_MIN:
            max_time_ = 60;
            break;
        case RTT_HOUR:
            max_time_ = 60 * 60;
            break;
        default:
            std::cout << "非法的滚动时间类型..." << std::endl;
            exit(2);
        }

        // 1.目录的创建
        std::string dir = ::util::File::getDirctory(prefix_);
        if (!::util::File::exist(dir))
        {
            if (!::util::File::createDirctory(dir))
            {
                std::cout << "create dirctory fail..." << std::endl;
                exit(1);
            }
        }
        // 2.创建文件
        createFile();
    }
    void sink(const char *log, size_t len)
    {
        if (::util::Date::now() - create_time_ >= max_time_)
        {
            // 当前文件超时了，需更新文件
            if (cur_ofs_.is_open())
                cur_ofs_.close();

            createFile();
        }
        cur_ofs_.write(log, len);
    }

private:
    void createFile()
    {
        static int count = 0;
        // 1.在prefix的基础上，得到一个完整的文件名
        // filename: prefix + 202311291817550.log
        std::stringstream ss;
        ss << prefix_;
        ::util::Date d;
        ss << d.year << d.month << d.day << d.hour << d.min << d.sec;
        ss << "-" << count++;
        ss << ".log";
        std::string filename = ss.str();

        // 2.根据文件名打开文件(在得到的目录下创建并打开)
        cur_ofs_.open(filename, std::ofstream::binary | std::ofstream::app);
        create_time_ = ::util::Date::now();
    }
};

void test()
{
    LoggerBuilder::Ptr builder = LoggerBuilderFactory::create<LocalLoggerBuilder>();
    builder->bulidName("RollbyTimeLogger");
    builder->buildSinker<RollByTimeLogSink>("rollfiles/bash-");
    Logger::Ptr logger = builder->build();

    size_t count = 0;
    time_t end = ckflogs::util::Date::now() + 5;
    while (ckflogs::util::Date::now() < end)
    {
        logger->error("%s-%d", "test log", count++);
    }
}

int main()
{
    test();
    return 0;
}